//
//  ContactData.m
//  DataTransfer
//
//  Created by 宋润理 on 2023/12/16.
//  Copyright © 2023 iCocos. All rights reserved.
//

#import "ContactData.h"

@implementation ContactData

+ (id)contactDataFromDict:(NSDictionary *)dict {
    ContactData *data = [[ContactData alloc] init];
    data.givenName = dict[@"givenName"];
    data.familyName = dict[@"familyName"];
    data.photoData = dict[@"photoData"];
    data.phoneNumbers = dict[@"phoneNumbers"];
    data.emailAddresses = dict[@"emailAddresses"];
    data.urlAddresses = dict[@"urlAddresses"];
    data.postalAddresses = dict[@"postalAddresses"];
    // 创建一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    // 创建一个NSCalendar对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    data.birthday = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay) fromDate:[dateFormatter dateFromString:dict[@"birthday"]]];
    return data;
}

// 将ContactData对象转为字典的方法
- (NSDictionary *)dictionaryFromContactData {
    // 创建一个NSCalendar对象
    NSCalendar *calendar = [NSCalendar currentCalendar];

    // 使用NSCalendar和NSDateComponents创建一个NSDate对象
    NSDate *date = [calendar dateFromComponents:self.birthday];

    // 创建一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    // 将NSDate对象转换为字符串
    NSString *dateString = [dateFormatter stringFromDate:date];
    
    return @{
        @"givenName": kSafeString(self.givenName),
        @"familyName": kSafeString(self.familyName),
        @"photoData": self.photoData ?: [NSNull null],
        @"phoneNumbers": self.phoneNumbers ?: [NSNull null],
        @"emailAddresses": self.emailAddresses ?: [NSNull null],
        @"urlAddresses": self.urlAddresses ?: [NSNull null],
        @"postalAddresses": self.postalAddresses ?: [NSNull null],
        @"birthday": kSafeString(dateString)
    };
}




@end
